<template>
    <el-main>
      <el-row style="margin:20px 0px">
        <my-Search :searchWay="true" :inputPlaceholder="'反馈简述'" @onSearch="getTitleSearchContent"></my-Search>
        <el-select style="margin-right:10px;width:110px" v-model="choiceStatusType" placeholder="反馈状态" @change="statusSearch"  clearable >
          <el-option
            v-for="(item,index) in statusType"
            :key="index"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-date-picker
          v-model="choiceDateTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          start-placeholder="反馈开始日期"
          end-placeholder="反馈结束日期"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          @blur="choiceDate"
          @change="choiceDate"
          >
        </el-date-picker>
        <el-button style="margin-left:10px" icon="el-icon-plus" type="info" size="medium" @click="addFeedback()">反馈问题</el-button>
        <el-button :disabled="selectTableRowId.length<=1" type="danger" icon="el-icon-delete-solid" size="medium" @click="deleteFeedbackBatch">批量删除</el-button>

      </el-row>

      <el-table @selection-change="selectTable" :height="tableHeight" row-key="id" ref="feedbackTableData" :data="feedbackTableData" :default-sort = "{prop: 'updateTime', order: 'descending'}" >
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <el-table-column prop="title" align="center" label="反馈简述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="createTime" align="center" label="反馈时间" width="200"></el-table-column>
        <el-table-column prop="updateTime" align="center" label="回复时间" width="200"></el-table-column>
        <el-table-column prop="gusername" align="center" label="回复人" width="120"></el-table-column>
        <el-table-column align="center" label="状态" width="150">
          <template slot-scope="scope">
            <el-alert v-if="scope.row.back!=null" title="已回复" type="success" show-icon center :closable="false" />
            <el-alert v-if="scope.row.back==null" title="待回复" type="warning" show-icon center :closable="false" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="260">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-view" size="small" @click="checkfeedback(scope.row)" >查看</el-button>
            <el-button type="danger" icon="el-icon-delete" size="small" @click="deletefeedback(scope.row)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区 -->
      <pagination
      ref="pagination"
      @pagination="getPagination"
      :total="parseInt(totalPage)"
      :page="parseInt(searchCondition.page)"
      :limit="parseInt(searchCondition.pageSize)"
      :pageSizes="paginationSize"
      ></pagination>

      <!-- 新增弹框 -->
      <my-dialog
        :title="feedbackDialog.title"
        :width="feedbackDialog.width"
        :height="feedbackDialog.height"
        :visible="feedbackDialog.visible"
        @onClose="onClose"
        @onConfirm="onConfirm"
      >
        <div slot="content">
          <el-form
            :model="feedbackFormData"
            ref="feedbackFormRef"
            :rules="rules"
            label-position="top"
            size="small"
          >
          <el-form-item prop="title" label="反馈简述">
            <el-input v-model="feedbackFormData.title" show-word-limit maxlength="40" clearable></el-input>
          </el-form-item>
          <el-form-item prop="content" label="反馈内容">
            <el-input
              type="textarea"
              maxlength="300"
              show-word-limit
              v-model="feedbackFormData.content"
              :rows="6"
              resize="none"
              placeholder="（限300字）"
            ></el-input>
          </el-form-item>

            <br/>
            <el-form-item size="small" label="附加问题说明图片(最多五张)">
              <el-upload
                :file-list="fileList"
                ref="pic"
                list-type="picture-card"
                :class="showUploadButton ? 'uoloadSty' : 'disUoloadSty'"
                action="#"
                :http-request="requestUpload"
                :on-preview="handlePictureCardPreview"
                multiple
                :limit="5"
                :on-exceed="handleExceed"
                accept=".png,.jpg,.jpeg"
                :before-upload="beforeUpload"
                :on-change="handleChange"
                :on-remove="handleRemove"
                >
                  <i slot="default" class="el-icon-plus"></i>
              </el-upload>
            </el-form-item>

          </el-form>
        </div>
      </my-dialog>

      <el-dialog title="反馈详情" append-to-body :visible.sync="feedbackVisible" :before-close="onfeedbackDialogClose">
        <div v-if="replyBack!=null&&replyBack!=''" class="replyFeedback">
          <p>回复人：{{replyUsername}}</p>
          <p>回复内容：{{replyBack}}</p>
        </div>
        <el-descriptions :title="feedbackTitle" :column="1" direction="vertical" :colon="false">
          <el-descriptions-item label="反馈内容">
            <div class="feedbackContent">
              {{feedbackContent}}
            </div>
          </el-descriptions-item>
          <el-descriptions-item v-if="feedbackFileList.length>0" label="反馈图片">
            <el-row type="flex"  >
              <el-col class="feedbackImg" v-for="(p,index) in feedbackFileList" :key="index">
                <el-image :src="p" :preview-src-list="feedbackFileList" fit="contain"></el-image>
              </el-col>
            </el-row>
          </el-descriptions-item>
        </el-descriptions>
      </el-dialog>

    </el-main>
</template>

<script>
import {getFeedbackListApi,addFeedbackApi,deleteFeedbackApi,deleteFeedbackBatchApi} from "@/api/feedback"
import { uploadPicturesApi, getPicturesByBidApi,deleteAllFilesApi} from "@/api/pictures";
import myDialog from "@/components/MyDialog/index";
import mySearch from "@/components/MySearch/index";
import pagination from "@/components/Pagination/index";
  export default {
    components: { myDialog,mySearch,pagination },
    data(){
      return {
        feedbackVisible:false,
        feedbackTitle:'',
        feedbackUsername:'',
        feedbackNid:'',
        feedbackDeptName:'',
        feedbackPhone:'',
        feedbackContent:'',
        replyUsername:'',
        replyBack:'',
        feedbackFileList:[],
        feedbackTableData:[],
        tableHeight:0,
        searchCondition :{
          uid:this.$store.getters.userId,
          nid:'',
          username:'',
          title:'',
          //1:已处理，0：未处理 空：全部
          status:'',
          startTime:'',
          endTime:'',
          page: 1,
          pageSize: 10,
        },
        statusType:[{label:"已回复",value:1},{label:"待回复",value:0}],
        //筛选项
        searchType:[{label:"学号/工号",value:"0"},{label:"姓名",value:"1"}],
        totalPage: 0,
        paginationSize: [5,10,30,50,100,200],
        choiceStatusType:'',
        choiceDateTime:'',
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              const end = new Date(new Date().setHours(23, 59, 59, 59));
              const start = new Date(new Date().setHours(0, 0, 0, 0));
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近一周',
            onClick(picker) {
              const end = new Date(new Date().setHours(23, 59, 59, 59));
              const start = new Date(new Date().setHours(0, 0, 0, 0));
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近一个月',
            onClick(picker) {
              const end = new Date(new Date().setHours(23, 59, 59, 59));
              const start = new Date(new Date().setHours(0, 0, 0, 0));
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          },{
            text: '最近半年',
            onClick(picker) {
              const end = new Date(new Date().setHours(23, 59, 59, 59));
              const start = new Date(new Date().setHours(0, 0, 0, 0));
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30 * 6);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        //被选中的行 携带Id
        selectTableRowId: [],
        //被选中的行 携带No
        selectTableRowNo: [],
        //分页容量
        paginationSize: [10,30,50],
        //查询返回 总记录数
        totalPage: 0,
        feedbackFormData:{
          title:'',
          content:'',
          uid:this.$store.getters.userId,
          no:'',
        },
        feedbackDialog: {
          title: '反馈问题',
          width: 924,
          height: 406,
          visible: false,
        },
        rules: {
          title: { required: true, trigger: "blur", message: "反馈简述不能为空" },
          content: { required: true, trigger: "blur", message: "反馈内容不能为空" },
        },
        //图片上传设置
        picsPreviewUrl: '',
        picsVisible: false,
        showUploadButton: true,
        fileList: [],
        deletePicsList: [],
      }
    },
    created(){
      this.getFeedbackList();
    },
    mounted() {
      this.$nextTick(() => {
        //有页码区就高度多-120
        this.tableHeight = window.innerHeight - 208 - 120;
      });
    },
    methods:{
      //批量删除
      async deleteFeedbackBatch() {
        let confirm = await this.$myconfirm("此操作不可逆！确定删除这些反馈吗？");
        if (confirm) {
          let deleteArray = this.selectTableRowId.toString();
          let deleteList = this.selectTableRowNo.toString();
          let res = await deleteFeedbackBatchApi({ids:deleteArray});
          if(res && res.code == 200){
            if(this.totalPage % this.searchCondition.pageSize ==this.selectTableRowId.length){
              this.searchCondition.page-=1;
            }
            //删除本地及数据库的图片
            await deleteAllFilesApi({bids: deleteList});
            this.getFeedbackList();
            this.$message.success(res.msg);
          }
        }
      },
      //选择
      selectTable(selection){
        this.selectTableRowId = [];
        this.selectTableRowNo = [];
        selection.forEach(item=>{
          this.selectTableRowId.push(item.id);
          this.selectTableRowNo.push(item.no);
        })
      },
      //删除
      async deletefeedback(row){
        let confirm = await this.$myconfirm("确定删除该反馈？");
        if (confirm) {
          let res = await deleteFeedbackApi({id:row.id});
          if(res&&res.code==200){
            await deleteAllFilesApi({bids: row.no});
            if(this.searchCondition.pageSize ==1 || this.totalPage % this.searchCondition.pageSize ==1){
              this.searchCondition.page-=1;
            }
            //删除本地及数据库的图片
            this.getFeedbackList();
            this.$message.success(res.msg);
          }
        }
      },
      //关闭查看反馈
      onfeedbackDialogClose(){
        this.feedbackVisible = false;
        this.feedbackFileList = [];
        this.feedbackTitle = '';
        this.feedbackUsername = '';
        this.feedbackNid = '';
        this.feedbackDeptName = '';
        this.feedbackPhone = '';
        this.feedbackContent = '';
        this.replyUsername = '';
        this.replyBack = '';
      },
      //查看反馈
      checkfeedback(row){
        this.getFeedbackPicturesByBid(row.no);
        this.feedbackTitle = row.title;
        this.feedbackUsername = row.username;
        this.feedbackNid = row.nid;
        this.feedbackDeptName = row.deptName;
        this.feedbackPhone = row.phone;
        this.feedbackContent = row.content;
        this.replyUsername = row.gusername;
        this.replyBack = row.back;
        this.feedbackVisible = true;
      },
      //获取图片
      async getFeedbackPicturesByBid(bid){
        let res = await getPicturesByBidApi({"bid":bid})
        if(res&&res.code==200){
          let copylist = res.data;
           copylist.filter(item=>{
            this.feedbackFileList.push(item.url);
          })
        }
      },

      //日期范围查询
      choiceDate(){
        if(this.choiceDateTime!=null){
          this.searchCondition.startTime = this.choiceDateTime[0];
          this.searchCondition.endTime = this.choiceDateTime[1];
        }else{
          this.searchCondition.startTime = '';
          this.searchCondition.endTime = '';
        }
        this.getFeedbackList();
      },
      //状态查询
      statusSearch(){
        this.searchCondition.status = this.choiceStatusType;
        this.getFeedbackList();
      },
      //标题查询
      getTitleSearchContent(val){
        this.searchCondition.title = val;
        this.getFeedbackList();
      },
      //内容查询
      getSearchContent(val,type){
        switch (type) {
          case '0':
            this.searchCondition.nid = val;
            this.searchCondition.username = '';
            break;
          case '1':
            this.searchCondition.nid = '';
            this.searchCondition.username = val;
            break;
          default:
            this.searchCondition.no = '';
            this.searchCondition.nid = '';
            break;
        }
        this.getFeedbackList();
      },
      //分页查询
      getPagination(val){
        this.searchCondition.page = val.page;
        this.searchCondition.pageSize = val.limit;
        this.getNoticeList();
      },
      //查询
      async getFeedbackList(){
        let res = await getFeedbackListApi(this.searchCondition)
        if(res&&res.code==200){
          this.totalPage = res.data.total
          this.feedbackTableData = res.data.list;
        }
      },
      async onConfirm(){
        let confirm = await this.$myconfirm("反馈后不能修改！确定反馈内容描述正确？");
        if (confirm) {
          let res = await addFeedbackApi(this.feedbackFormData);
          if(res&&res.code==200){
            //上传反馈图片
            let readyUploadList = [];
            this.$refs.pic.uploadFiles.forEach(item=>{
              if(item.status==="ready"){
                readyUploadList.push(item)
              }
            })
            if(readyUploadList.length>0){
              let bid = this.feedbackFormData.no;
              this.uploadPictures(readyUploadList,bid)
            }
            this.getFeedbackList();
            this.$message.success(res.msg);
            this.onClose();
          }
        }
      },
      onClose(){
        this.$refs.pic.uploadFiles = [];
        this.deletePicsList = [];
        this.isShowUploadButton(this.fileList);
        this.$refs.feedbackFormRef.resetFields();
        this.feedbackDialog.visible = false;
      },
      addFeedback(){
        this.feedbackFormData.no = this.getId();
        this.feedbackDialog.visible = true;
      },
      //获取随机数id生成反馈编号
      getId() {
        let date = Date.now();
        let rund = Math.ceil(Math.random()*1000)
        let id = 'feedback'+date+''+ rund;
        return id;
      },

      // 覆盖默认的上传行为
      requestUpload() {
      },
      // 上传预处理
      beforeUpload(file) {
        if (file.type.indexOf("image/") === -1) {
          this.$message.error("文件格式错误，请上传类型如：JPG、PNG后缀的图片！");
          return false;
        }
        if (file.size> 3145728) {
          this.$message.error("请上传大小不超过3MB的图片！");
          return false;
        }
        return true;
      },
      handleExceed(){
        this.$message.info("最多选择上传五张图片，请重新选择！");
      },
      //删除图片
      handleRemove(file,filelist) {
        if(file.status==="success"){
          this.deletePicsList.push(file.id);
        }
        this.isShowUploadButton(filelist.length)
      },
      //提交图片
      handleChange(file,filelist){
        this.isShowUploadButton(filelist.length)
      },
      //预览图片
      handlePictureCardPreview(file) {
        this.picsPreviewUrl = file.url;
        this.picsVisible = true;
      },
      //判断是否显示上传按钮
      isShowUploadButton(listLength){
        if(listLength >= 5){
          this.showUploadButton = false;
        }else{
          this.showUploadButton = true;
        }
      },
      //获取图片
      async getPicturesByBidApi(bid){
        let res = await getPicturesByBidApi({"bid":bid})
        if(res&&res.code==200){
          this.fileList = res.data;
          this.isShowUploadButton(this.fileList.length);
        }
      },
      //上传图片
      async uploadPictures(list,bid){
        let formData = new FormData();
        list.forEach(item=>{
          formData.append("files",item.raw);
        })
        formData.append("bid",bid);
        await uploadPicturesApi(formData);
      },
    }
  }
</script>

<style lang="scss" scoped>
  .replyFeedback{
    font-size:16px;
    line-height: 20px;
    padding: 10px 30px;
    margin-bottom: 20px;
    background-color:#ddd;
    border-radius: 4px;
  }
  .feedbackContent{
    font-size: 18px;
    line-height:24px;
    text-indent: 2em;
    margin-bottom:30px;
  }
  .feedbackImg{
    width:130px;
    height:130px;
    margin-left: 40px;
  }

  .uoloadSty ::v-deep .el-upload--picture-card{
    width: 148px;
    height: 148px;
    line-height: 146px
    }
  .disUoloadSty ::v-deep .el-upload--picture-card{
    display:none;
    }
  .uoloadSty ::v-deep .el-upload-list__item {
    transition: none !important;
  }
  .disUoloadSty ::v-deep .el-upload-list__item {
    transition: none !important;
  }
</style>
